package com.heba.greenmulu.scan;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.heba.ATApp;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.config.CommonConfig;
import com.heba.bean.PhotoObject;
import com.heba.dialog.CustomDialogView;
import com.heba.dialog.ErrorDialog;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.MemberShipHelper;
import com.heba.helper.TakePhotoHelper;
import com.heba.permission.PermissionHelper;
import com.heba.popupwindow.PhotoPopupWindow;
import com.heba.utils.DensityUtils;
import com.heba.utils.FileSizeUtils;
import com.heba.utils.ImageTools;
import com.heba.utils.ImageUtils;
import com.heba.utils.UniversalImageLoadTool;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.CosXmlSimpleService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.transfer.TransferStateListener;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider;
import com.yanzhenjie.permission.Permission;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * 新增产品页面
 * <p>
 * Created by jason on 2019/2/27.
 */

public class ItemAddProductActivity extends BaseActivity {

    private View view_background;
    private EditText edit_barcode_num;
    private EditText edit_brand_name;
    private EditText edit_product_name;
    private EditText edit_weight;
    private EditText edit_ingredients;
    private EditText edit_remark1;
    private EditText edit_remark2;
    private LinearLayout linear_photo_view;
    private Button btn_submit;

    /**
     * 图片上传
     */
    private PhotoPopupWindow photoPopupWindow;
    private File tempFile;
    private String imgUrl = "";
    private String uploadPath = "";

    /**
     * 腾讯云文件存储对象
     */
    private CosXmlServiceConfig serviceConfig;
    private CosXmlSimpleService cosXmlSimpleService;
    private String appid = "1253933048";
    private String region = "ap-guangzhou";

    private int[] ids = new int[]{R.string.front_packaging_photo, R.string.nutrition_label_photo, R.string.ingredients_photo, R.string.more_photo};
    private int pos = 0;  //用于取出linear_photo_view对应的子view

    private ArrayList<PhotoObject> photoObjects = new ArrayList<>();
    private String barcodeNum = "";   //接收传递的barcodeNum

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_product_report_error);
        initTopbar();
        findViewById();
        initView();
        initCosClient();
        initPopWindow();
        updateImageUploadView();
    }

    /**
     * 初始化cosClient
     */
    private void initCosClient() {
        //初始化 cosClient
        serviceConfig = new CosXmlServiceConfig.Builder().setAppidAndRegion(appid, region).setDebuggable(true).builder();
        /**
         * 初始化对象，来给SDK提供临时密钥。
         */
        QCloudCredentialProvider credentialProvider = new ShortTimeCredentialProvider(ATApp.CosSecretId,
                ATApp.CosSecretKey, 300);
        cosXmlSimpleService = new CosXmlSimpleService(this, serviceConfig, credentialProvider);
    }

    @Override
    protected void findViewById() {
        view_background = findViewById(R.id.view_background);
        edit_barcode_num = findViewById(R.id.edit_barcode_num);
        edit_brand_name = findViewById(R.id.edit_brand_name);
        edit_product_name = findViewById(R.id.edit_product_name);
        edit_weight = findViewById(R.id.edit_weight);
        edit_ingredients = findViewById(R.id.edit_ingredients);
        edit_remark1 = findViewById(R.id.edit_remark1);
        edit_remark2 = findViewById(R.id.edit_remark2);
        linear_photo_view = findViewById(R.id.linear_photo_view);
        btn_submit = findViewById(R.id.btn_submit);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.create_product));

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            barcodeNum = bundle.getString(CommonConfig.BARCODE, "");
        }

        edit_barcode_num.setFocusable(false);
        edit_barcode_num.setFocusableInTouchMode(false);
        edit_barcode_num.setEnabled(false);
        edit_barcode_num.setText(barcodeNum);

        /**
         * 提交错误信息
         */
        btn_submit.setOnClickListener(v -> {
            uploadProductData();
        });

        /**
         * back
         */
        img_back.setOnClickListener(v -> {
            showBackDialog();
        });
    }

    /**
     * 初始化PopupWindow
     */
    private void initPopWindow() {
        photoPopupWindow = new PhotoPopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dip2px(this, 165));

        photoPopupWindow.setOnPhotoPopupClickListener(new PhotoPopupWindow.OnPhotoPopupClickListener() {
            @Override
            public void onCameraClick() {
                tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                TakePhotoHelper.takePicture(ItemAddProductActivity.this, tempFile);
            }

            @Override
            public void onAlbumClick() {
                tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                TakePhotoHelper.selectPhoto(ItemAddProductActivity.this);
            }

            @Override
            public void onCancelClick() {

            }
        });

        photoPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 上传产品数据
     */
    private void uploadProductData() {
        /**
         * check empty
         */
        if (edit_brand_name.getText().toString().isEmpty()) {
            ErrorDialog.Show(this, getResources().getString(R.string.tips), getResources().getString(R.string.input_brand_name));
            return;
        }

        if (edit_product_name.getText().toString().isEmpty()) {
            ErrorDialog.Show(this, getResources().getString(R.string.tips), getResources().getString(R.string.input_product_name));
            return;
        }

        if (edit_weight.getText().toString().isEmpty()) {
            ErrorDialog.Show(this, getResources().getString(R.string.tips), getResources().getString(R.string.input_weight));
            return;
        }

        /**
         * 判断有无上传图片
         */
        if (photoObjects.isEmpty()) {
            ErrorDialog.Show(this, getResources().getString(R.string.tips), getResources().getString(R.string.please_upload_photo));
            return;
        }

        /**
         * 判断必须上传前两张图片
         */
        for (int i = 0; i < 2; i++) {
            View view = linear_photo_view.getChildAt(i);
            RelativeLayout relative_product_view = view.findViewById(R.id.relative_product_view);
            if (i == 0) {
                if (relative_product_view.getVisibility() == View.INVISIBLE) {
                    ErrorDialog.Show(this, getResources().getString(R.string.tips), getResources().getString(R.string.please_upload_front_photo));
                    return;
                }
            } else {
                if (relative_product_view.getVisibility() == View.INVISIBLE) {
                    ErrorDialog.Show(this, getResources().getString(R.string.tips), getResources().getString(R.string.please_upload_nutrition_photo));
                    return;
                }
            }
        }

        progressDialog.show();
        /**
         * 上传产品资料
         */
        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {
                progressDialog.dismiss();
                //上传成功，显示成功对话框
                showSuccessDialog();
            }

            @Override
            public void Fail(String error) {
                progressDialog.dismiss();
            }
        }).addProduct(this, barcodeNum, edit_brand_name.getText().toString(), edit_product_name.getText().toString(), edit_weight.getText().toString(),
                edit_ingredients.getText().toString(), edit_remark1.getText().toString(), edit_remark2.getText().toString(), generatePhotoJson());

    }

    /**
     * 图片url生成pathJson
     *
     * @return
     */
    private String generatePhotoJson() {
        //list排序,根据id升序
        Collections.sort(photoObjects, new Comparator<PhotoObject>() {
            @Override
            public int compare(PhotoObject o1, PhotoObject o2) {
                return o1.getID() > o2.getID() ? 1 : -1;
            }
        });

        try {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < photoObjects.size(); i++) {
                JSONObject d = new JSONObject();
                d.put("Url", photoObjects.get(i).getImageUrl());
                jsonArray.put(jsonArray.length(), d);
            }
            Debug.Log("jsonArray PathJson", jsonArray.toString());
            return jsonArray.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取摄像头,读取文件权限
     */
    private void getCameraPermission() {
        new PermissionHelper(ItemAddProductActivity.this, new PermissionHelper.PermissionListener() {
            @Override
            public void onPermissionSuccess() {
                photoPopupWindow.showAtLocation(linear_photo_view, Gravity.BOTTOM, 0, 0);
            }

            @Override
            public void onPermissionFailure() {

            }
        }).requestPermission(Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
    }

    /**
     * 添加上传照片框框
     */
    private void updateImageUploadView() {
        linear_photo_view.removeAllViews();
        for (int i = 0; i < ids.length; i++) {
            linear_photo_view.addView(updateImageUploadRowView(ids[i], i));
        }
    }

    /**
     * updateImageUploadRowView
     *
     * @return view
     */
    private View updateImageUploadRowView(int id, int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_upload_photo, null);
        ImageView img_upload = view.findViewById(R.id.image_photo);
        ImageView img_photo1 = view.findViewById(R.id.image_photo1);
        TextView txt_content = view.findViewById(R.id.txt_content);
        RelativeLayout relative_product_view = view.findViewById(R.id.relative_product_view);
        ImageView img_product = view.findViewById(R.id.img_product);
        ImageView img_delete = view.findViewById(R.id.img_product_delete);
        txt_content.setText(getResources().getString(id));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((DensityUtils.getWidth(this) - DensityUtils.dip2px(this, 20)) / 4,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(params);

        /**
         * upload photo
         */
        img_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pos = position;
                view_background.setVisibility(View.VISIBLE);
                getCameraPermission();
            }
        });

        /**
         * delete photo
         */
        img_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                img_upload.setVisibility(View.VISIBLE);
                img_photo1.setVisibility(View.VISIBLE);
                txt_content.setVisibility(View.VISIBLE);
                relative_product_view.setVisibility(View.INVISIBLE);
                img_product.setImageBitmap(null);
                if (!photoObjects.isEmpty()) {
                    for (int i = 0; i < photoObjects.size(); i++) {
                        PhotoObject photoObject = photoObjects.get(i);
                        if (photoObject.getID() == position) {
                            photoObjects.remove(photoObject);
                        }
                    }
                    Debug.Log("delete", photoObjects.toString());
                }
            }
        });
        return view;
    }

    /**
     * 拍照回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TakePhotoHelper.TAKE_PICTURE:
                    //拍照处理
                    if (tempFile != null) {
                        String pathFile = "file://" + tempFile.toString();

                        View view = linear_photo_view.getChildAt(pos);
                        ImageView img_product = view.findViewById(R.id.img_product);
                        ImageView img_upload = view.findViewById(R.id.image_photo);
                        ImageView img_photo1 = view.findViewById(R.id.image_photo1);
                        TextView txt_content = view.findViewById(R.id.txt_content);
                        RelativeLayout relative_product_view = view.findViewById(R.id.relative_product_view);
                        img_upload.setVisibility(View.INVISIBLE);
                        img_photo1.setVisibility(View.INVISIBLE);
                        txt_content.setVisibility(View.INVISIBLE);
                        relative_product_view.setVisibility(View.VISIBLE);
                        ImageLoader.getInstance().displayImage(pathFile, img_product,
                                UniversalImageLoadTool.getImageOption(R.drawable.btn_upload_image));

                        //图片路径
//                        String localPath = tempFile.toString();
//                        String cosPath = "transfer_" + ImageTools.getFileName();

                        /**
                         * 压缩并上传图片
                         */
                        compressImage(pathFile);

                    }
                    break;

                case TakePhotoHelper.CHOOSE_PICTURE:
                    //相册选取处理
                    if (data != null) {
                        try {
                            Uri imageUri = data.getData();

                            /**
                             * uri转成图片文件实际路径，并旋转图片角度
                             */
//                            String path = ImageTools.handleImageOnKitKat(this, data);
//                            Bitmap bitmap = BitmapFactory.decodeFile(path);
//                            int degree = RotateBitmap.readPictureDegree(path);
//                            bitmap = ImageTools.rotaingImageView(bitmap, degree);

                            View view = linear_photo_view.getChildAt(pos);
                            ImageView img_product = view.findViewById(R.id.img_product);
                            ImageView img_upload = view.findViewById(R.id.image_photo);
                            ImageView img_photo1 = view.findViewById(R.id.image_photo1);
                            TextView txt_content = view.findViewById(R.id.txt_content);
                            RelativeLayout relative_product_view = view.findViewById(R.id.relative_product_view);
                            img_upload.setVisibility(View.INVISIBLE);
                            img_photo1.setVisibility(View.INVISIBLE);
                            txt_content.setVisibility(View.INVISIBLE);
                            relative_product_view.setVisibility(View.VISIBLE);
                            ImageLoader.getInstance().displayImage(imageUri.toString(), img_product,
                                    UniversalImageLoadTool.getImageOption(R.drawable.btn_upload_image));

                            //图片路径
//                            String localPath = ImageTools.handleImageOnKitKat(this, data);
//                            String cosPath = "transfer_" + ImageTools.getFileName();
                            /**
                             * 压缩并上传图片
                             */
                            compressImage(imageUri.toString());

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 压缩图片大小
     *
     * @param pathFile
     * @return
     */
    private String compressImage(String pathFile) {
        ImageSize targetSize = new ImageSize(700, 700);
        ImageLoader.getInstance().loadImage(pathFile, targetSize,
                UniversalImageLoadTool.getImageOption(R.drawable.btn_upload_image),
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        super.onLoadingComplete(imageUri, view, loadedImage);
                        if (loadedImage != null && !loadedImage.isRecycled()) {
                            Bitmap bitmap = ImageUtils.compressImageOptions(loadedImage, 100); //压缩图片质量
                            //压缩后的图片文件路径
                            uploadPath = ImageTools.savePhotoToSDCard(ItemAddProductActivity.this, bitmap,
                                    ImageTools.getUploadPathFolder(), ImageTools.getFileName(), false);
                            String cosPath = "greenmulu/image/transfer_" + ImageTools.getFileName();
                            upload(uploadPath, cosPath);
                            Debug.Log("upload file length is  ---->",
                                    FileSizeUtils.getFileOrFilesSize(uploadPath, 2) + "KB");
                        }
                    }
                });
        return uploadPath;
    }

    /**
     * 上传文件
     *
     * @param srcPath
     * @param cosPath
     */
    private void upload(String srcPath, String cosPath) {
        // 初始化 TransferConfig
        TransferConfig transferConfig = new TransferConfig.Builder().build();
        TransferManager transferManager = new TransferManager(cosXmlSimpleService, transferConfig);

        String bucket = "greenmulu";
        String uploadId = null;//用于续传，若无，则为null.
        //上传文件
        COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath, srcPath, uploadId);
        //设置上传进度回调
        cosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(long complete, long target) {
                float progress = 1.0f * complete / target * 100;
                Debug.Log("upload", String.format("progress = %d%%", (int) progress));
            }
        });
        progressDialog.show();
        //设置返回结果回调
        cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                progressDialog.dismiss();
                Debug.Log("upload", "Success: " + result.printResult());
                if (!result.accessUrl.startsWith("http://") && !result.accessUrl.startsWith("https://")) {
                    imgUrl = "http://" + result.accessUrl;
                } else {
                    imgUrl = result.accessUrl;
                }
                PhotoObject object = new PhotoObject();
                object.setID(pos);
                object.setImageUrl(imgUrl);
                photoObjects.add(object);
                Debug.Log("upload success", photoObjects.toString());
            }

            @Override
            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                progressDialog.dismiss();
                Debug.Log("upload", "Failed: " + (exception == null ? serviceException.getMessage() : exception.toString()));
            }
        });
        //设置任务状态回调, 可以查看任务过程
        cosxmlUploadTask.setTransferStateListener(new TransferStateListener() {
            @Override
            public void onStateChanged(TransferState state) {
                Debug.Log("upload", "Task state:" + state.name());
            }
        });
    }

    /**
     * 显示对话框
     */
    private void showBackDialog() {
        new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
            @Override
            public void onYesClick() {
                new CustomDialogView(new CustomDialogView.OnSelectEditDialogClickListener() {
                    @Override
                    public void onYesClick(boolean select1, boolean select2, boolean select3, boolean select4, String content) {
                        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                            @Override
                            public void Success() {
                                finishActivity();
                            }

                            @Override
                            public void Fail(String error) {

                            }
                        }).discardProduct(ItemAddProductActivity.this, select1, select2, select3, select4, content);
                    }

                    @Override
                    public void onNoClick() {

                    }
                }).showDialogWithSelectAndEditText(ItemAddProductActivity.this);
            }

            @Override
            public void onNoClick() {

            }
        }).showDialogWithButton(this, getResources().getString(R.string.discard_product_submission), getResources().getString(R.string.discard_content),
                getResources().getString(R.string.discard), getResources().getString(R.string.cancel));
    }

    /**
     * 提交成功显示的对话框
     */
    private void showSuccessDialog() {
        new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
            @Override
            public void onYesClick() {

            }

            @Override
            public void onNoClick() {
                finishActivity();
            }
        }).showDialogWithButton(this, getResources().getString(R.string.contribute_title), getResources().getString(R.string.contribute_content),
                "", getResources().getString(R.string.dismiss));
    }

    @Override
    protected void onResume() {
        super.onResume();
        //需要释放camera资源
        Cfg.isNeedToReleaseCamera = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Debug.Log("清理上传图片的文件夹", ImageTools.getUploadPathFolder().toString());
        //清理文件图片
        ImageTools.deleteAllPhoto(ImageTools.getUploadPathFolder());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            showBackDialog();
        }
        return super.onKeyDown(keyCode, event);
    }
}
